package com.jjyu.service.impl;

import com.jjyu.entity.Reservation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Service
public class ReservationServiceImpl {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // RowMapper for mapping SQL result to Reservation object
    private static class ReservationRowMapper implements RowMapper<Reservation> {
        @Override
        public Reservation mapRow(ResultSet rs, int rowNum) throws SQLException {
            Reservation reservation = new Reservation();
            reservation.setId(rs.getLong("id"));
            reservation.setCustomerName(rs.getString("customer_name"));
            reservation.setCustomerPhone(rs.getString("customer_phone"));
            reservation.setReservationDate(rs.getDate("reservation_date").toLocalDate());
            reservation.setReservationTime(rs.getTime("reservation_time").toLocalTime());
            reservation.setPartySize(rs.getInt("party_size"));
            reservation.setSpecialRequests(rs.getString("special_requests"));
            reservation.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime());
            return reservation;
        }
    }

    // Create reservation
    public int saveReservation(Reservation reservation) {
        String sql = "INSERT INTO reservation (customer_name, customer_phone, reservation_date, reservation_time, party_size, special_requests) " +
                "VALUES (?, ?, ?, ?, ?, ?)";
        return jdbcTemplate.update(sql, reservation.getCustomerName(), reservation.getCustomerPhone(),
                reservation.getReservationDate(), reservation.getReservationTime(), reservation.getPartySize(),
                reservation.getSpecialRequests());
    }

    // Retrieve a reservation by ID
    public Reservation getReservationById(Long id) {
        String sql = "SELECT * FROM reservation WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new ReservationRowMapper(), id);
    }

    // Retrieve all reservations
    public List<Reservation> getAllReservations() {
        String sql = "SELECT * FROM reservation";
        return jdbcTemplate.query(sql, new ReservationRowMapper());
    }

    // Delete a reservation by ID
    public int deleteReservationById(Long id) {
        String sql = "DELETE FROM reservation WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }
}
